package com.kxmall.pay.abc.controller.receive;

import cn.dev33.satoken.annotation.SaIgnore;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kxmall.common.utils.Base64Util;
import com.kxmall.common.utils.DateUtil;
import com.kxmall.pay.abc.beans.QueryBillRequest;
import com.kxmall.pay.abc.beans.QueryBillResponse;
import com.kxmall.pay.abc.sign.SignatureAndVerification;
import com.kxmall.user.domain.KxUser;
import com.kxmall.user.mapper.KxUserMapper;
import com.kxmall.vehicle.domain.KxVehicleBoxGoodsOrder;
import com.kxmall.vehicle.domain.KxVehicleBoxUpGoods;
import com.kxmall.vehicle.domain.KxVehicleInGoods;
import com.kxmall.vehicle.mapper.KxVehicleBoxGoodsOrderMapper;
import com.kxmall.vehicle.mapper.KxVehicleBoxUpGoodsMapper;
import com.kxmall.vehicle.mapper.KxVehicleInGoodsMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Map;

/**
 * 账单查询(金额规则为0的)
 *
 */
@Api(tags = "账单查询(金额规则为0的)")
@Slf4j
@Controller
@RequestMapping("/merchant")
public class QueryBillController {

	public static final String YYYYMMDDHHMMSSSSS = "yyyyMMddHHmmssSSS";

	@Value("${coffee.merchantID}")
	private String merchantID = "103881054280033";

	//签名工具类
	@Autowired
	private SignatureAndVerification signatureAndVerification;
	@Autowired
	private KxUserMapper userMapper;
	@Autowired
	private KxVehicleInGoodsMapper vehicleInGoodsMapper;
	@Autowired
	private KxVehicleBoxUpGoodsMapper vehicleBoxUpGoodsMapper;
	@Autowired
	private KxVehicleBoxGoodsOrderMapper vehicleBoxGoodsOrderMapper;
	// ************************************单账单情景begin*****************************************************************************************
	/**
	 * 账单查询接口(金额规则为0的)
	 * 
	 * @param queryRequest
	 * @param request
	 * @param httpResponse
	 */
	@SaIgnore
	@ApiOperation(value = "/merchant/getDirectJoinMerchBill.do - 账单查询接口(金额规则为0的)", httpMethod = "POST")
	@RequestMapping(value = "/getDirectJoinMerchBill.do", method = RequestMethod.POST)
	@ResponseBody
	public void getBill4DirectJoinMerch(String queryRequest,
			HttpServletRequest request, HttpServletResponse httpResponse) {
		log.info("进入QueryBillController账单查询接口--------(金额规则为0的)-------");
		String responseJson = null;
		try {
			//接收报文request返回截取并返回requsetBody和使用base64解析后的requsetBody
			Map<String,String> requestMap = signatureAndVerification.requestBodyOfBase64(request);
			//使用base64解析完成后的requsetBody
			String requsetBodyOfDecoded = requestMap.get("requsetBodyOfDecoded");
			//解析前的requsetBody
			String requsetBody = requestMap.get("requsetBody");
			//获取缴费中心传送过来的签名
			String signatureString = requestMap.get("signatureString");
			QueryBillRequest queryBillRequest = JSON.parseObject(requsetBodyOfDecoded,
					new TypeReference<QueryBillRequest>() {
					});
			// 验签
			signatureAndVerification.read_cer_and_verify_sign(requsetBody, signatureString);
			//交易编号
			String traceNo = queryBillRequest.getMessage().getInfo().getTraceNo();
			KxVehicleBoxGoodsOrder vehicleBoxGoodsOrder = vehicleBoxGoodsOrderMapper.selectOne(
					new LambdaQueryWrapper<KxVehicleBoxGoodsOrder>()
					.eq(KxVehicleBoxGoodsOrder::getOrderNo,traceNo));

			KxVehicleBoxUpGoods vehicleBoxUpGoods = vehicleBoxUpGoodsMapper.selectOne(
					new LambdaQueryWrapper<KxVehicleBoxUpGoods>()
							.eq(KxVehicleBoxUpGoods::getId,vehicleBoxGoodsOrder.getUpGoodsId()));

			KxVehicleInGoods vehicleInGoods = vehicleInGoodsMapper.selectOne(
					new LambdaQueryWrapper<KxVehicleInGoods>()
							.eq(KxVehicleInGoods::getId,vehicleBoxUpGoods.getInGoodsId()));

			KxUser user = userMapper.selectOne(new LambdaQueryWrapper<KxUser>()
					.eq(KxUser::getUid,vehicleBoxGoodsOrder.getUserId()));
			//返回给缴费中心的响应
			QueryBillResponse response = new QueryBillResponse(queryBillRequest);
			QueryBillResponse.Message respMessage = response.getMessage();
			QueryBillResponse.Message.Head respHead = response.getMessage().getHead();
			QueryBillResponse.Message.Info respInfo = response.getMessage().getInfo();
			ArrayList<QueryBillResponse.Message.Info.Bill> respBills = new ArrayList<QueryBillResponse.Message.Info.Bill>();
			ArrayList<QueryBillResponse.Message.Info.Bill.DescDetail> respDescDetail = new ArrayList<QueryBillResponse.Message.Info.Bill.DescDetail>();
			QueryBillResponse.Message.Info.Bill respBill = respInfo.new Bill();
			respBill.setBillNo(queryBillRequest.getMessage().getInfo().getTraceNo());
			respBill.setBillName(vehicleInGoods.getProductName());
			respBill.setFeeAmt("0.00");
			respBill.setExpireDate(DateUtil.getCurDate4Str());
			respBill.setDescDetails(respDescDetail);
			respBill.setRcvMerchantId(merchantID);
			respBills.add(respBill);
			String epayCode = queryBillRequest.getMessage().getInfo().getEpayCode();
			respInfo.setEpayCode(epayCode);
			String merchantId = queryBillRequest.getMessage().getInfo().getMerchantId();
			respInfo.setMerchantId(merchantId);
			respInfo.setTraceNo(traceNo);
			//根据输入停车场标示返回商户号 账单查询接口根据停车上唯一标示返回两条商户ID（103881104410001，103881104990018）
			//String parkInput = queryBillRequest.getMessage().getInfo().getInput1();
			//log.info("--------parkInput------------"+parkInput);
			//if("001".equals(parkInput)){
			//	respBill.setRcvMerchantId("103881104410001");
			//}else if("002".equals(parkInput)){
			//	respBill.setRcvMerchantId("103881104990018");
			//}
			respInfo.setInput1(queryBillRequest.getMessage().getInfo().getInput1());
			respInfo.setInput2(queryBillRequest.getMessage().getInfo().getInput2());
			respInfo.setInput3(queryBillRequest.getMessage().getInfo().getInput3());
			respInfo.setInput4(queryBillRequest.getMessage().getInfo().getInput4());
			respInfo.setInput5(queryBillRequest.getMessage().getInfo().getInput5());
			respInfo.setCustName(user.getUsername());
			respInfo.setCustAddress(user.getAddres());
			respInfo.setCacheMem("0,0.00,S,张三丰,4340152");
			respInfo.setRemark("备注信息为空");
			respInfo.setCallBackText("中国农业银行官网");
//			respInfo.setCallBackUrl("https://abcsr.keepfx.cn/b/ejy/payResult/");
//			使用base64加密信息
			respInfo.setCallBackUrl(Base64Util.encodeData("https://mall.mosunshine.com/merchant/getRequest4Sale.do"));
			//金额规则字段
			String amtRule = "0";
			respInfo.setAmtRule(amtRule);
			QueryBillResponse.Message.Info.Bill.UnitDetail unitDetail =
			respBill.new UnitDetail(vehicleInGoods.getProductName(), vehicleBoxGoodsOrder.getAmount().toString(), vehicleBoxGoodsOrder.getCount().toString());
			respBill.setUnitDetail(unitDetail);
			respBill.setOweAmt(vehicleBoxGoodsOrder.getAmount().toString());
			respBill.setFeeAmt("0.00");
			QueryBillResponse.Message.Info.Bill.DescDetail descDtail1 =
					respBill.new DescDetail(vehicleInGoods.getCategoryName(), vehicleInGoods.getProductName());
			respDescDetail.add(descDtail1);
			respBill.setDescDetails(respDescDetail);
			respInfo.setTotalBillCount("1");
			respInfo.setBill(respBills);
			log.info("----------------------账单查询成功0");
			respHead.setReturnCode("0000");
			respHead.setReturnMessage("账单查询成功，返回成功标志");
			respHead.setTransFlag("02");
			respHead.setTimeStamp(DateUtil.get(YYYYMMDDHHMMSSSSS));
			respMessage.setInfo(respInfo);
			respMessage.setHead(respHead);
			response.setMessage(respMessage);
			responseJson = JSON.toJSONString(response);
			// 加签名
			String signatrue = signatureAndVerification.signWhithsha1withrsa(responseJson);
			log.info("signatrue" + responseJson);
			log.info("responseJson打印结果是（responseJson加密前）:" + responseJson);
			responseJson = signatrue + "||" + new String(Base64.encodeBase64(responseJson.getBytes("utf-8")));
			log.info("responseJson打印结果是（responseJson加密后）:" + responseJson);
			httpResponse.setCharacterEncoding("utf-8");
			httpResponse.setContentType("text/plain");
			httpResponse.getWriter().write(responseJson);

			vehicleBoxGoodsOrder.setOrderStatus(1);
			vehicleBoxGoodsOrder.setBranchCode(queryBillRequest.getMessage().getHead().getBranchCode());
			vehicleBoxGoodsOrder.setChannel(queryBillRequest.getMessage().getHead().getChannel());
			vehicleBoxGoodsOrder.setEpayCode(queryBillRequest.getMessage().getInfo().getEpayCode());
			vehicleBoxGoodsOrder.setMerchantId(queryBillRequest.getMessage().getInfo().getMerchantId());
			vehicleBoxGoodsOrder.setTraceNo(queryBillRequest.getMessage().getInfo().getTraceNo());
			vehicleBoxGoodsOrder.setTraceUserId(queryBillRequest.getMessage().getInfo().getUserId());
			vehicleBoxGoodsOrder.setTransCode(queryBillRequest.getMessage().getHead().getTransCode());
			vehicleBoxGoodsOrder.setTransFlag(queryBillRequest.getMessage().getHead().getTransFlag());
			vehicleBoxGoodsOrder.setTransSeqNum(queryBillRequest.getMessage().getHead().getTransSeqNum());
			vehicleBoxGoodsOrder.setTimeStamp(queryBillRequest.getMessage().getHead().getTimeStamp());
			vehicleBoxGoodsOrder.setInput1(queryBillRequest.getMessage().getInfo().getInput1());
			vehicleBoxGoodsOrder.setInput2(queryBillRequest.getMessage().getInfo().getInput2());
			vehicleBoxGoodsOrder.setInput3(queryBillRequest.getMessage().getInfo().getInput3());
			vehicleBoxGoodsOrder.setInput4(queryBillRequest.getMessage().getInfo().getInput4());
			vehicleBoxGoodsOrder.setInput5(queryBillRequest.getMessage().getInfo().getInput5());
			int result = vehicleBoxGoodsOrderMapper.updateById(vehicleBoxGoodsOrder);
			if(result > 0) {
				log.info("vehicleBoxGoodsOrderMapper.updateById() success!!! vehicleBoxGoodsOrder:{}",vehicleBoxGoodsOrder.toString());
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
